"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : ustore-逻辑复制
Case Name   : 在逻辑解码中创建复制槽
Create At   : 2022/5/6
Owner       : @wan005
Description :
        1.修改wal_level为logical;enable_slot_log为on;enable_default_ustore_table为on
        2.配置逻辑复制的白名单用户
        3..验证修改后的参数是否生效
        4.创建逻辑复制槽
        5.执行逻辑复制槽流式解码
        6.删除逻辑复制槽
        7.恢复初始值
Expect      :
        1.成功
        2.成功
        3.成功
        4.成功
        5.解码无报错
        6.成功
        7.成功
History     :
"""
import os
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class LogicalReplication(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.constant = Constant()
        self.common = Common()
        self.primary_node = Node('PrimaryDbUser')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pg_hba = os.path.join(macro.DB_INSTANCE_PATH,
                                   macro.PG_HBA_FILE_NAME)
        self.us_name = "u_logical_replication_case0011"
        self.slot_name = "slot_logical_replication_case0011"
        self.decode_file = os.path.join(macro.DB_INSTANCE_PATH, 'logical1.txt')
        self.default_value1 = self.common.show_param('wal_level')
        self.default_value2 = self.common.show_param('enable_slot_log')
        self.default_value3 = \
            self.common.show_param('enable_default_ustore_table')

    def test_logicreplication(self):
        self.log.info(f'-----{os.path.basename(__file__)}' + ' start-----')

        text = '--step1:修改wal_level为logical;enable_slot_log为on;' \
               'enable_default_ustore_table;expect:成功--'
        self.log.info(text)
        mod_msg = self.pri_sh.execute_gsguc('set',
                                            self.constant.GSGUC_SUCCESS_MSG,
                                            'wal_level =logical')
        self.log.info(mod_msg)
        self.assertTrue(mod_msg, "执行失败" + text)
        mod_msg = self.pri_sh.execute_gsguc('set',
                                            self.constant.GSGUC_SUCCESS_MSG,
                                            'enable_slot_log =on')
        self.log.info(mod_msg)
        self.assertTrue(mod_msg, "执行失败" + text)
        result = self.pri_sh.execute_gsguc("set",
                                        self.constant.GSGUC_SUCCESS_MSG,
                                            f"enable_default_ustore_table=on")
        self.assertTrue(result, "执行失败" + text)

        text = '--step2:配置逻辑复制的白名单用户;expect:成功--'
        self.log.info(text)
        sql_cmd = self.pri_sh.execut_db_sql(f'''drop role if exists \
            {self.us_name};
            create role {self.us_name} with login password \
            '{macro.COMMON_PASSWD}';
            alter role {self.us_name} with replication sysadmin;''')
        self.log.info(sql_cmd)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, sql_cmd,
                      '执行失败:' + text)
        self.assertIn(self.constant.ALTER_ROLE_SUCCESS_MSG, sql_cmd,
                      '执行失败:' + text)
        mod_msg = f"sed -i '$a\local    replication     {self.us_name}      " \
                  f"trust'   {self.pg_hba}"
        self.log.info(mod_msg)
        msg = self.primary_node.sh(mod_msg).result()
        self.log.info(msg)
        mod_msg = f"sed -i '$a\host    replication     " \
                  f"{self.us_name}   127.0.0.1/32   trust'   {self.pg_hba}"
        self.log.info(mod_msg)
        msg = self.primary_node.sh(mod_msg).result()
        self.log.info(msg)
        mod_msg = f"sed -i '$a\host   replication     " \
                  f"{self.us_name}   ::1/128    trust'  {self.pg_hba}"
        self.log.info(mod_msg)
        msg = self.primary_node.sh(mod_msg).result()
        self.log.info(msg)
        restart_msg = self.pri_sh.restart_db_cluster()
        self.log.info(restart_msg)
        status = self.pri_sh.get_db_cluster_status()
        self.assertTrue("Degraded" in status or "Normal" in status,
                        '执行失败:' + text)

        text = '--step3:验证修改后的参数是否生效;expect:成功'
        self.log.info(text)
        result1 = self.pri_sh.execut_db_sql("show wal_level;")
        result2 = self.pri_sh.execut_db_sql("show enable_slot_log;")
        result3 = self.pri_sh.execut_db_sql("show enable_default_ustore_table;")
        self.log.info(result1)
        self.log.info(result2)
        self.log.info(result3)
        self.assertIn("logical", result1, "执行失败:" + text)
        self.assertIn("on", result2, "执行失败:" + text)
        self.assertIn("on", result3, "执行失败:" + text)

        text = '--step4:创建逻辑复制槽;expect:成功--'
        self.log.info(text)
        create_cmd = f"pg_recvlogical -d postgres " \
                     f"-U {self.us_name} " \
                     f"-S {self.slot_name} " \
                     f"-p {self.primary_node.db_port} " \
                     f"-P mppdb_decoding " \
                     f"--create"
        execute_cmd = f'''source {macro.DB_ENV_PATH}
                   expect <<EOF
                   set timeout 300
                   spawn {create_cmd}
                   expect "Password:"
                   send "{macro.COMMON_PASSWD}\\n"
                   expect eof\n''' + '''EOF'''
        self.log.info(execute_cmd)
        exec_msg = self.primary_node.sh(execute_cmd).result()
        self.log.info(exec_msg)
        self.assertNotIn('FATAL' or 'error', exec_msg, text + '执行失败')

        text = '--step5:执行逻辑复制槽流式解码;expect:解码无报错--'
        self.log.info(text)
        decode_cmd = f"pg_recvlogical -d postgres " \
                     f"-U {self.us_name} " \
                     f"-S {self.slot_name} " \
                     f"-p {self.primary_node.db_port} " \
                     f"--start " \
                     f"-f {self.decode_file} " \
                     f"-s 2 " \
                     f"-v " \
                     f"-P mppdb_decoding "
        execute_cmd = f'''source {macro.DB_ENV_PATH}
                           expect <<EOF
                           set timeout 300
                           spawn {decode_cmd}
                           expect "Password:"
                           send "{macro.COMMON_PASSWD}\\n"
                           expect eof\n''' + '''EOF'''
        self.log.info(execute_cmd)
        exec_msg = self.primary_node.sh(execute_cmd).result()
        self.log.info(exec_msg)
        self.assertIn('confirming write up to', exec_msg, text + '执行失败')
        self.assertNotIn('FATAL' and 'error', exec_msg, text + '执行失败')

    def tearDown(self):
        text = '--step6:删除逻辑复制槽;expect:成功--'
        self.log.info(text)
        del_cmd = f"pg_recvlogical -d postgres " \
                  f"-U {self.us_name} " \
                  f"-S {self.slot_name} " \
                  f"-p {self.primary_node.db_port} " \
                  f" --drop"
        self.log.info(del_cmd)
        execute_cmd = f'''source {macro.DB_ENV_PATH}
                          expect <<EOF
                          set timeout 300
                          spawn {del_cmd}
                          expect "Password:"
                          send "{macro.COMMON_PASSWD}\\n"
                          expect eof\n''' + '''EOF'''
        self.log.info(execute_cmd)
        exec_msg = self.primary_node.sh(execute_cmd).result()
        self.log.info(exec_msg)
        self.assertIn('', exec_msg, '执行失败:' + text)

        text = '--step7:恢复初始值;expect:成功--'
        self.log.info(text)
        sql_cmd = self.pri_sh.execut_db_sql(f'''drop role if exists \
        {self.us_name};''')
        self.log.info(sql_cmd)
        del_msg = f"sed -i '/{self.us_name}/d' {self.pg_hba}"
        self.log.info(del_msg)
        msg = self.primary_node.sh(del_msg).result()
        self.log.info(msg)
        res_cmd1 = self.pri_sh.execute_gsguc('set',
                                            self.constant.GSGUC_SUCCESS_MSG,
                                            f'wal_level='
                                            f'{self.default_value1}')
        self.log.info(res_cmd1)
        res_cmd2 = self.pri_sh.execute_gsguc('set',
                                            self.constant.GSGUC_SUCCESS_MSG,
                                            f'enable_slot_log='
                                            f'{self.default_value2}')
        self.log.info(res_cmd2)
        result = self.pri_sh.execute_gsguc('set',
                                           self.constant.GSGUC_SUCCESS_MSG,
                                           f'enable_default_ustore_table='
                                           f'{self.default_value3}')
        self.log.info(res_cmd1)
        self.log.info(result)
        self.assertTrue(res_cmd1, "执行失败" + text)
        self.assertTrue(res_cmd2, "执行失败" + text)
        self.assertTrue(result, "执行失败" + text)
        restart_msg = self.pri_sh.restart_db_cluster()
        self.log.info(restart_msg)
        status = self.pri_sh.get_db_cluster_status()
        self.assertTrue("Degraded" in status or "Normal" in status,
                        '执行失败:' + text)
        self.log.info(f'-----{os.path.basename(__file__)}' + ' end-----')

